<!-- 楼宇管理 -->
<template>
  <div class="app-container">
    <div class="app-form">
      <el-form
        ref="tablePage"
        :inline="true"
        :model="tablePage"
      >
        <el-form-item label="楼宇名称" prop="name">
          <el-input v-model="tablePage.name" size="small" placeholder="请输入" clearable @input="screening" />
        </el-form-item>
        <el-form-item style="margin-left:25px;">
          <!-- <el-button type="primary" size="small" @click="screening">查询</el-button> -->
          <!-- <el-button type="default" size="small" @click="reset('tablePage')">重置</el-button> -->
          <el-button type="success" size="small" @click="add">新建</el-button>
          <el-button v-show="isShowDel" type="danger" size="small" @click="delAll">删除</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格部分 须放在mytablebox盒子下面自定义样式才有效果 -->
      <div class="mytablebox">
        <vxe-table
          ref="xTable"
          align="center"
          :round="true"
          :data="tableData"
          height="100%"
          :export-config="{}"
          header-row-class-name="headerName"
          @checkbox-all="selectAllEvent"
          @checkbox-change="selectChangeEvent"
        >
          <vxe-table-column type="checkbox" width="60" fixed="left" />
          <vxe-table-column field="parkId" title="所属园区" show-overflow />
          <vxe-table-column field="name" title="楼宇名称" show-overflow />
          <vxe-table-column field="region" title="区域" show-overflow />
          <vxe-table-column field="totalHeight" title="楼层总数" show-overflow />
          <vxe-table-column field="id" title="楼宇ID" show-overflow />
          <vxe-table-column field="note" title="描述" show-overflow />
          <vxe-table-column field="aspect" title="楼宇朝向" show-overflow />
          <vxe-table-column field="elevator" title="是否有电梯" show-overflow >
            <template #default="{row}">
              <span v-if="row.elevator === 1">是</span>
              <span v-else>否</span>
            </template>
          </vxe-table-column>
          <vxe-table-column field="time" title="创建时间" show-overflow formatter="formatDate" sortable />
          <vxe-table-column field="creatName" title="创建人" show-overflow />
          <vxe-table-column title="操作" fixed="right" width="150">
            <template v-slot="{ row }">
              <vxe-button status="primary" content="编辑" @click="update(row)" />
              <!-- <vxe-button status="default" content="楼层" @click="floorEvent(row)" /> -->
              <vxe-button status="danger" content="删除" @click="delOne(row.id)" />
            </template>
          </vxe-table-column>
        </vxe-table>
      </div>
      <!-- 分页部分 -->
      <vxe-pager
        :current-page="tablePage.page"
        :page-size="tablePage.limit"
        :total="tablePage.total"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Total']"
        @page-change="handlePageChange"
      />
    </div>
    <el-dialog
      title="操作"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="30%"
      :show-close="false"
    >
      <el-form ref="ruleForm" :model="form" status-icon :rules="rules" label-width="130px">
        <el-form-item label="所属园区" prop="parkId">
          <el-select v-model="form.parkId" placeholder="请选择园区">
            <el-option v-for="(item,index) in parkData" :key="index" :label="item.name" :value="parseInt(item.id)" />
          </el-select>
        </el-form-item>
        <el-form-item label="楼宇名称" prop="name">
          <el-input v-model="form.name" type="text" />
          <!-- <el-select v-model="form.name" placeholder="请选择楼宇名称">
            <el-option v-for="(item,index) in names" :key="index" :label="item.name" :value="item.name" />
          </el-select> -->
        </el-form-item>
        <el-form-item label="区域" prop="region">
          <el-input v-model="form.region" type="text" />
        </el-form-item>
        <el-form-item label="楼层数" prop="totalHeight">
          <el-input v-model="form.totalHeight" type="text" />
        </el-form-item>
        <el-form-item label="是否有电梯" prop="elevator">
          <el-select v-model="form.elevator" placeholder="请选择是否有电梯">
            <el-option label="是" value="是"></el-option>
            <el-option label="否" value="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼宇朝向" prop="aspect">
          <el-select v-model="form.aspect" placeholder="请选择楼宇朝向">
            <el-option label="东" value="东"></el-option>
            <el-option label="南" value="南"></el-option>
            <el-option label="西" value="西"></el-option>
            <el-option label="北" value="北"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.note" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="reset('ruleForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="楼层列表"
      :visible.sync="dialogVisible2"
      :close-on-click-modal="false"
      :before-close="handleClose"
      width="50%"
    >
      <el-row style="margin-bottom:20px;">
        <el-col :span="2"><el-button type="success" size="small" @click="add2">新建</el-button></el-col>
        <el-col :span="2"><el-button v-show="isShowDel2" type="danger" size="small" @click="delAll2">删除</el-button></el-col>
      </el-row>
      <div style="height:200px;">
        <vxe-table
          ref="xTable2"
          align="center"
          :round="true"
          :data="tableData2"
          height="100%"
          :export-config="{}"
          header-row-class-name="headerName2"
          @checkbox-all="selectAllEvent2"
          @checkbox-change="selectChangeEvent2"
        >
          <vxe-table-column type="checkbox" width="60" fixed="left" />
          <vxe-table-column field="num" title="楼层" show-overflow />
          <vxe-table-column field="name" title="楼层名称" show-overflow />
          <vxe-table-column field="time" title="创建时间" show-overflow formatter="formatDate" sortable />
          <vxe-table-column field="crateName" title="创建人" show-overflow />
          <vxe-table-column title="操作" fixed="right">
            <template v-slot="{ row }">
              <vxe-button status="primary" content="编辑" @click="update2(row)" />
              <vxe-button status="danger" content="删除" @click="delOne2(row.id)" />
            </template>
          </vxe-table-column>
        </vxe-table>
        <vxe-pager
        :current-page="tablePage2.page"
        :page-size="tablePage2.limit"
        :total="tablePage2.total"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Total']"
        @page-change="handlePageChange"
      />
      </div>
    </el-dialog>
    <el-dialog
      title="操作"
      :visible.sync="dialogVisible3"
      :close-on-click-modal="false"
      width="30%"
      :show-close="false"
    >
      <el-form ref="ruleForm2" :model="form2" status-icon :rules="rules2" label-width="100px">
        <el-form-item label="楼层" prop="num">
          <el-input v-model="form2.num" autocomplete="off" />
        </el-form-item>
        <el-form-item label="楼层名称" prop="name">
          <el-input v-model="form2.name" autocomplete="off" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm2('ruleForm2')">提交</el-button>
          <el-button @click="reset('ruleForm2')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import Cookies from 'js-cookie'
import XEUtils from 'xe-utils'
import {getBuildingInfo, addBuildingInfo,putBuildingInfoById, delBuildingInfoByIdList} from '@/api/parkManage'
import {addFloorInfo, getFloorInfo, putFloorInfo, getParkInfo } from '@/api/parkManage'
import {getParkInfoById} from '@/api/Data_filling'
export default {
// import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    // 这里存放数据
    return {
      username: '',
      dialogVisible: false,
      list: [],
      tablePage: {
        page: 1,
        limit: 10,
        total: 0,
        name: null
      },
      // 表格内数据
      tableData: [],
      // 选中数据
      records: [],
      isShowDel: false,
      form: {
        parkId: null,
        name: null,
        region: null,
        totalHeight: null,
        note: null,
        creatName: null,
        aspect: null,
        elevator:null
      },
      rules: {
        parkId: [{ required: true, message: '请选择园区', trigger: 'change' }],
        name: [
          { required: true, message: '请输入楼宇名称', trigger: 'change' }
        ],
        note: [{ required: true, message: '请输入描述', trigger: 'blur' }],
        aspect: [{ required: true, message: '请输入楼宇朝向', trigger: 'change' }],
        elevator: [{ required: true, message: '请选择是否有电梯', trigger: 'blur' }],
        region: [{ required: true, message: '请输入区域', trigger: 'blur' }],
        totalHeight: [{ required: true, message: '请输入楼层数', trigger: 'blur' }],
      },
      parkData: [],
      //编辑还是新增
      addOrEdit: 0,
      dialogVisible2: false,
      form2: {
        num: null,
        name: null,
      },
      rules2: {
        num: { required: true, message: '请输入楼层', trigger: 'blur' },
        name: { required: true, message: '请输入楼层名称', trigger: 'blur' }
      },
      isShowDel2: false,
      tableData2: [],
      tablePage2: {
        page: 1,
        limit: 10,
        total: 0,
      },
      list2: [],
      records2: [],
      dialogVisible3: false,
      addOrEdit2: 0,
      // 楼栋
      floors:null,
      parkId: Cookies.get('parkId'),
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getPartInfo()
    this.getUserInfo()
    this.init(this.tablePage.page, this.tablePage.limit)
    // this.init2(this.tablePage2.page, this.tablePage2.limit)
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {},
  // 方法集合
  methods: {
    // 园区的信息
    getPartInfo(){
      getParkInfoById(this.parkId).then(res => {
          console.log("园区信息", res)
          this.parkData = [{id: res.data.id, name: res.data.name}]
        })
    },
    // 获取用户信息
    getUserInfo(){
      this.$store.dispatch('user/getInfo').then(res => {
        console.log('user info', res)
        this.username = res.user.nickname
      })
    },
    init(page, limit) {
      getBuildingInfo(page, limit).then(res => {
        console.log('get111 res', res)
        this.list = res.data
        this.tableData = res.data
        this.tablePage.total = res.count
        // 楼栋
        let floorList = []
        res.data.forEach( item => {
            floorList.push(item.name)
        })
        this.floors = floorList
      })
    },
    init2(page, limit){
      getFloorInfo(page, limit).then(res => {
        console.log('get222 res', res)
        this.list2 = res.data.records
        this.tableData2 = res.data.records
        this.tablePage2.total = res.data.total
      })
    },
    // 筛选
    screening() {
      const filterVal = XEUtils.toValueString(this.tablePage.name).trim().toLowerCase()
      const filterRE = new RegExp(filterVal, 'gi')
      const searchProps = ['name']
      const rest = this.list.filter(item => searchProps.some(key => XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterVal) > -1))
      this.tableData = rest.map(row => {
          const item = Object.assign({}, row)
          searchProps.forEach(key => {
          item[key] = XEUtils.toValueString(item[key]).replace(filterRE, match => `${match}`)
          })
          return item
      })
    },
    // 重置
    reset(formName) {
      this.$refs[formName].resetFields()
      this.dialogVisible = false
      this.dialogVisible3 = false
    },
    // 新建
    add() {
      this.addOrEdit = 0
      this.form = {}
      this.dialogVisible = true
    },
    add2() {
      this.addOrEdit2 = 0
      this.form2 = {}
      this.dialogVisible3 = true
    },
    // 删除
    delAll() {
      this.$confirm('此操作将永久删除选中数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let idList = []
        for (let i=0; i<this.records.length; i++) {
            idList.push(this.records[i].id)
        }
        // idList = JSON.stringify(idList)
        idList = idList.join(",")
        // this.records = []
        delBuildingInfoByIdList(idList).then(res => {
          console.log('del res', res)
          this.$refs.xTable.clearCheckboxRow()
          this.isShowDel = false
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.init(this.tablePage.page, this.tablePage.limit)
        })
        
      }).catch(() => {
        this.records = []
        this.$refs.xTable.clearCheckboxRow()
        this.isShowDel = false
        this.$message({type: 'info',message: '已取消删除'})
      })
    },
    delAll2() {
      this.$confirm('此操作将永久删除选中数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.records2 = []
        this.$refs.xTable2.clearCheckboxRow()
        this.isShowDel2 = false
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.records2 = []
        this.$refs.xTable2.clearCheckboxRow()
        this.isShowDel2 = false
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 表格全选事件
    selectAllEvent({ records, checked }) {
      this.records = records
      if (checked) this.isShowDel = true
      else this.isShowDel = false
    },
    selectAllEvent2({ records, checked }) {
      this.records2 = records
      if (checked) this.isShowDel2 = true
      else this.isShowDel2 = false
    },
    // 表格单行选择事件
    selectChangeEvent({ records, checked }) {
      this.records = records
      if (checked) this.isShowDel = true
      else this.isShowDel = false
    },
    selectChangeEvent2({ records, checked }) {
      this.records2 = records
      if (checked) this.isShowDel2 = true
      else this.isShowDel2 = false
    },
    handlePageChange({ currentPage, pageSize }) {
      this.tablePage.page = currentPage
      this.tablePage.limit = pageSize
      this.init(currentPage, pageSize)
    },
    handleClose() {
      this.records2 = []
      this.$refs.xTable2.clearCheckboxRow()
      this.isShowDel2 = false
      this.dialogVisible2 = false
    },
    update(row) {
      this.addOrEdit = 1
      this.form = JSON.parse(JSON.stringify(row))
      console.log(this.form)
      if(this.form['elevator'] == 1){
        this.form['elevator'] = '是'
      }else{
        this.form['elevator'] = '否'
      }
      this.dialogVisible = true
    },
    update2(row) {
      this.addOrEdit2 = 1
      this.form2 = JSON.parse(JSON.stringify(row))
      this.dialogVisible3 = true
    },
    floorEvent(row) {
      this.dialogVisible2 = true
    },
    delOne(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delBuildingInfoByIdList(id).then(res => {
          console.log('del res', res)
          this.$refs.xTable.clearCheckboxRow()
          this.isShowDel = false
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.init(this.tablePage.page, this.tablePage.limit)
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    delOne2(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialogVisible = false
          if(this.form['elevator'] == '是'){
              this.form['elevator'] = 1
            }else{
              this.form['elevator'] = 0
            }
          if(this.addOrEdit == 0){
            this.form['creatName'] = this.username
            console.log('this.form', this.form)
            if(this.form['note'] == undefined){
              this.form['note'] = '无'
            }
            let nameList = [this.form['name']]
            // 不能添加重复的楼栋信息
            let result = []
            result = this.floors.filter(val => nameList.includes(val))
            if(result.length == 0){
              addBuildingInfo(this.form).then(res => {
                console.log('add111 res', res)
                this.init(this.tablePage.page, this.tablePage.limit)
              })
            }else{
              this.$message.error('请不要填写重复的楼栋名称！');
            }
            
          }else{
            putBuildingInfoById(this.form).then(res => {
              console.log('update111 res', res)
              this.init(this.tablePage.page, this.tablePage.limit)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
      
    },
    
  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.app-container{
  display: flex;
}
</style>
